<?php

namespace app\mini\controller;

use app\company\model\StoreSalesman;
use app\company\model\StoreSupplier;
use app\company\model\StoreUserAccount;
use app\company\model\Supplier;
use app\company\model\StoreUser as StoreUserModel;
use app\mini\model\Store;
use think\Response;

class StoreUser extends Base
{
    /**
     * 获取余额
     * @return Response
     */
    public function balance(): Response
    {
        $money = StoreUserAccount::where('store_user_id', $this->userInfo->id)
                                 ->value('money');
        return $this->success('获取成功', compact('money'));
    }

    /**
     * 获取门店列表
     */
    public function store(): Response
    {
        $param = request()->param();
        $sql   = new StoreSalesman();
        if (isset($param['name']) && $param['name']) {
            $storeIds = Store::where('name', 'like', '%' . $param['name'] . '%')
                             ->column('id');
            $sql      = $sql->whereIn('store_id', $storeIds);
        }
        $sql   = $sql->where('store_user_id', $this->userInfo->id);
        $count = $sql->count();
        $list  = $sql->field('store_id,store_user_id')
                     ->order('id', 'desc')
                     ->page($param['page'], $param['limit'])
                     ->select()
                     ->each(function ($item) {
                         $store            = Store::where('id', $item->store_id)
                                                  ->find();

                         $item->store_name = $store->name;
                         //TODO 设计的有问题，拿第一个为门店负责人，未来不好区分（如删除），之后重新设计
                         $store_user = StoreUserModel::where('store_id',$item->store_id)->find();
                         $item->store_user = $store_user->real_name;
                         $item->mobile = $store_user->mobile;
                         //查询经销商id
                         $supplier_ids = StoreSupplier::where('store_id', $item->store_id)->column('supplier_id');
                         $supplier_name = Supplier::where('id', 'in', $supplier_ids)->column('name');
                         $item->supplier_name = implode(',', $supplier_name);
                         $item->address = $store->address;
                         $item->is_on_credit = $store->is_on_credit;
                     });
        return $this->success('获取成功', compact('count', 'list'));
    }
}